﻿@page "/Account/Logout"

@rendermode InteractiveServer
@attribute [ReuseTabsPage(Ignore = true)]

@layout SageKing.Blazor.OpenIdService.Components.Layout.LoginLayout

<PageTitle>Logout</PageTitle>

<div class="centerall">
	@if (isSuccess)
	{
		<h2 class="text-danger">@Msg</h2>
	}
	else
	{
		<h1><a @onclick="signout" class="text-danger">@Msg</a></h1>
	}
</div>


@code {
	string? Msg = "正在退出中。。。。";
	int timeLimit = 3;//限制退出时间，防止死循环
	bool isSuccess = true;

	[SupplyParameterFromQuery]
	private string? ReturnUrl { get; set; }

	[CascadingParameter]
	[Inject] public AuthenticationStateProvider AuthProvider { get; set; }

	public CustomAuthStateProvider AuthStateProvider
	{
		get
		{
			return (CustomAuthStateProvider)AuthProvider;
		}
	}

	[Inject]
	public NavigationManager _NavigationManager { get; set; }

	protected override async Task OnInitializedAsync()
	{
		await signout();
	}

	private async Task signout()
	{
		try
		{
			isSuccess = await AuthStateProvider.SignOut();
			Msg = isSuccess ? $"退出成功,{timeLimit}秒后跳到登录界面！" : "退出失败，请手动直接退出。";
			if (isSuccess)
			{
				while (timeLimit > 0)
				{
					Msg = $"退出成功,{timeLimit}秒后跳到登录界面！";
					timeLimit--;
					StateHasChanged();
					await Task.Delay(1000);
				}
				_NavigationManager.NavigateTo($"{OpenIddictUIConstants.LoginURL}?ReturnUrl={ReturnUrl.UrlEncode()}&flag=logout", true);
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
			_NavigationManager.NavigateTo("/", true);
		}
	}
}